package com.magenta.maxoptra.gis.utils;

import java.util.Date;
import java.util.TimeZone;

/**
 * Project: MaxOptra
 * User: kaganov
 * Date: 03.10.2008 16:05:15
 * <p/>
 * Copyright (c) 1999-2007 Magenta Corporation Ltd. All Rights Reserved.
 * Magenta Technology proprietary and confidential.
 * Use is subject to license terms.
 */
public class TimeZoneUtils {

    private static final TimeZone serverTimezone = TimeZone.getTimeZone("UTC");
    //Samara zone for simpler development now.
    //TimeZone.getTimeZone(System.getConfProperty("user.timezone"));

    public static TimeZone getServerTimezone() {
        return serverTimezone;
    }

    public static Date currentTime() {
        return new Date();
    }

    public static Date getServerCurrentTime() {
        return getTimeInTimeZone(currentTime(), getServerTimezone(), true);
    }

    public static Date currentTimeInTimeZone(TimeZone timeZone) {
        return getTimeInTimeZone(currentTime(), timeZone, true);
    }

    public static Date getTimeInTimeZone(Date date, TimeZone timeZone, boolean isSeasonSpecified) {
        if (date == null) {
            return null;
        }
        if (timeZone == null) {
            throw new IllegalStateException("time zone is undefined");
        }
        int offset = offset(date, timeZone, isSeasonSpecified);
        return new Date(date.getTime() + offset);
    }

    public static Date getGMTTime(Date date, TimeZone timeZone, boolean isSeasonSpecified) {
        if (date == null) {
            return null;
        }
        int offset = offset(date, timeZone, isSeasonSpecified);
        return new Date(date.getTime() - offset);
    }

    private static int offset(Date date, TimeZone timeZone, boolean isSeasonSpecified) {
        //TimeZone.setDefault(TimeZoneUtils.getServerTimezone());
        long season = isSeasonSpecified ? date.getTime() : new Date().getTime();
        return timeZone.getOffset(season);
    }

}
